<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/qgg_blog/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/qgg_blog/lib/pace/pace-theme-center-atom.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/qgg_blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/qgg_blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/qgg_blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/qgg_blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/qgg_blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/qgg_blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/qgg_blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="perl," />










<meta name="description" content="前言说一下这个想法的由来。其实最初目的不是为了获取天气的，这只是一个练习而已。最初是想自动获取公司的出勤情况，提醒我前一天有没有忘记打卡的。公司打卡是由网站可以查询的，有时忘记了或者系统出错，可能当天打卡没有打上，不去查看的话就记为缺勤了（这可是关乎工资啊啊啊啊），于是想到了每天定时执行一次查询任务，要是差到有缺勤记录就在登录系统时发出提示。所以作为一个初学者我就自然想到怎么获取网站固定信息了。由">
<meta property="og:type" content="article">
<meta property="og:title" content="用perl脚本获取天气">
<meta property="og:url" content="https://zhang_de_shuai.gitee.io/qgg_blog/2020/02/14/%E7%94%A8perl%E8%84%9A%E6%9C%AC%E8%8E%B7%E5%8F%96%E5%A4%A9%E6%B0%94/index.html">
<meta property="og:site_name" content="圭木的博客">
<meta property="og:description" content="前言说一下这个想法的由来。其实最初目的不是为了获取天气的，这只是一个练习而已。最初是想自动获取公司的出勤情况，提醒我前一天有没有忘记打卡的。公司打卡是由网站可以查询的，有时忘记了或者系统出错，可能当天打卡没有打上，不去查看的话就记为缺勤了（这可是关乎工资啊啊啊啊），于是想到了每天定时执行一次查询任务，要是差到有缺勤记录就在登录系统时发出提示。所以作为一个初学者我就自然想到怎么获取网站固定信息了。由">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/7777712-35e2c8321a38a1d1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/7777712-3f1bc4ea75aee397.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="article:published_time" content="2020-02-14T07:15:18.000Z">
<meta property="article:modified_time" content="2020-02-14T07:48:31.940Z">
<meta property="article:author" content="一只圭工">
<meta property="article:tag" content="perl">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/7777712-35e2c8321a38a1d1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/qgg_blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zhang_de_shuai.gitee.io/qgg_blog/2020/02/14/用perl脚本获取天气/"/>





  <title>用perl脚本获取天气 | 圭木的博客</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/qgg_blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">圭木的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/qgg_blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/qgg_blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/qgg_blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/qgg_blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zhang_de_shuai.gitee.io/qgg_blog/qgg_blog/2020/02/14/%E7%94%A8perl%E8%84%9A%E6%9C%AC%E8%8E%B7%E5%8F%96%E5%A4%A9%E6%B0%94/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="一只圭工">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/qgg_blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="圭木的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">用perl脚本获取天气</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-02-14T15:15:18+08:00">
                2020-02-14
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/qgg_blog/categories/%E6%95%99%E7%A8%8B/" itemprop="url" rel="index">
                    <span itemprop="name">教程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量 <i class="fa fa-file-o"></i
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.5k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>说一下这个想法的由来。其实最初目的不是为了获取天气的，这只是一个练习而已。最初是想自动获取公司的出勤情况，提醒我前一天有没有忘记打卡的。公司打卡是由网站可以查询的，有时忘记了或者系统出错，可能当天打卡没有打上，不去查看的话就记为缺勤了（这可是关乎工资啊啊啊啊），于是想到了每天定时执行一次查询任务，要是差到有缺勤记录就在登录系统时发出提示。所以作为一个初学者我就自然想到怎么获取网站固定信息了。由于在公司是内网，无法在家测试，所以就写个查询天气的脚本来确定基本的脚本结构。</p>
<h1 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h1><p>原理呢，其实就是字符串的处理。我知道可以用网站的api发出请求，然后返回数据，这样更加方便快捷。<strong>但是</strong>，我不是学软件的不会这个，233333。当然 这不是理由，可以去学，只是有更简便的方式。我选择将网页源码下载下来然后分析字符获取字段，毕竟如果登录网页能看到信息，那么在网页的html里应该也有这个字段。那么现在大概的步骤就明确了：</p>
<hr>
<ol>
<li>下载网页源码。</li>
<li>查看源码，分析关键字段的特征，从而能够查找匹配。</li>
</ol>
<hr>
<p>这种方式只适合不需要网页交互的查询，假如查询时还要输入密码这些就不能查到了。只要在浏览器直接输入网址就能访问的网页可以用这种方法查询需要的信息。</p>
<h1 id="详细分析"><a href="#详细分析" class="headerlink" title="详细分析"></a>详细分析</h1><p>在这里我选取<a href="www.weather.com.cn/weather1d/101020100.shtml">中国天气网上海天气</a>来作为查询的网址。首先用浏览器将网页另存为html格式，然后查看文本内容（<strong>在这里推荐使用代码编辑器查看，浏览器有浏览网页源码功能的也可以查看</strong>。我将网页文件传到树莓派用vim查看了，后面perl也是在树莓派上写）。用vim查看代码，然后搜索日期，天气应该是按日期来排的。太幸运了，直接就搜到了：</p>
<p><img src="https://upload-images.jianshu.io/upload_images/7777712-35e2c8321a38a1d1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="天气信息所在行">实在是easy啊。那么我们来分析这一行。</p>
<blockquote>
<input type="hidden" id="hidden_title" value="10月27日20时 周五  晴转多云  16/22°C" />
</blockquote>
<p>这一行的分析思路有以下几点：</p>
<ul>
<li>这一句是通过搜索日期的到的，那么我们可以在代码中使用<strong>查找日期</strong>来定位这一行。</li>
<li>我们需要的天气信息在<code>value=</code>关键词后面用双引号包起来的字段，我们可以在定位行后在行里定位字符串<code>value=</code>,相信这不难做到。最简单粗暴的方式就是用数组把每个字符保存起来，然后一个一个遍历。这一行的字符也不多，占用内存也不大。</li>
<li>我还发现，我需要的字段被双引号<code>&quot;</code>包起来，那么我联想到perl中的<code>split</code>函数。可以将这一行用<code>split</code>函数将字符分解为以<code>&quot;</code>隔开的列表，这样我们只要访问列表元素就可以了。</li>
</ul>
<h1 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h1><p>首先使用shell的<code>curl</code>命令下载网页。这里解释一下为什么不用<code>perl</code>的命令（当然是因为技术不好啊^_^）。perl对网络的操作好像需要一些模块，不知道这些模块是安装<code>perl</code>时自带的还是需要额外添加，也不确定公司的<code>perl</code>是不是带有这些模块。但是shell的<code>curl</code>命令是自带的，我就使用shell命令来下载网页了。在<code>perl</code>中调用shell命令表达如下：</p>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">`curl -o wether.html http:<span class="regexp">//</span>www.weather.com.cn<span class="regexp">/weather/</span><span class="number">101020100</span>.shtml`</span><br></pre></td></tr></table></figure>
<p>注意两边的单引号！网址中的<code>101020100.shtml</code>指的是上海的天气页面，不清楚具体城市编码方式，可以一个一个去网站查询看。命令中的<code>-o wether.html</code>参数指的是将下载的网页另存为<code>wether.html</code>文件。<br>下载好网页后就可以以文本方式读取网页内容了。在处理文件字符之前，我们需要获得查询的关键字，也就是<strong>日期</strong>。获得关键字后去读取文件每一行，并判断当前行是否<strong>包含关键字</strong>，包含关键字则将当前行<strong>分解为列表</strong>，得到列表就可以输出天气信息了。<br>最后得到代码如下：</p>
<figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/perl -w</span></span><br><span class="line"> <span class="string">`curl -o wether.html http://www.weather.com.cn/weather/101020100.shtml`</span>;</span><br><span class="line"> <span class="keyword">if</span> ( ! <span class="keyword">open</span> HTML,<span class="string">'&lt;'</span>,<span class="string">'wether.html'</span> ) &#123;</span><br><span class="line">       <span class="keyword">die</span> <span class="string">"cannot open:$!"</span>;   <span class="comment">#文件打开失败提示</span></span><br><span class="line"> &#125;</span><br><span class="line"> $date =<span class="string">`date`</span>;  <span class="comment">#获取当前时间</span></span><br><span class="line"> <span class="keyword">chomp</span>($date);</span><br><span class="line"> @date_list = <span class="keyword">split</span> <span class="regexp">/\s+/</span>,$date; <span class="comment">#将获取到的时间以空格分解，提取出日期。也可以通过控制</span></span><br><span class="line">                                 <span class="comment">#获取时间命令的参数来直接获得日期。比如  date "+%m月%d日"</span></span><br><span class="line">                                 <span class="comment">#这样就可以直接获取"x月x日"格式的时间</span></span><br><span class="line"><span class="keyword">while</span> (<span class="keyword">defined</span> ($line = &lt;HTML&gt;)) &#123;      <span class="comment">#读取文件每一行到$line变量里</span></span><br><span class="line">$gre=(<span class="keyword">grep</span> <span class="regexp">/$date_list[2]/</span>,$line) + (<span class="keyword">grep</span> <span class="regexp">/value=/</span>,$line);<span class="comment">#如果有日期，又有value关键词，则认为找到了</span></span><br><span class="line"><span class="keyword">if</span> ($gre == <span class="number">2</span>)&#123;</span><br><span class="line">      @val_list=<span class="keyword">split</span> <span class="regexp">/"/</span>,$line;      <span class="comment">#将文本行以"为分隔符分解字段</span></span><br><span class="line">      <span class="keyword">print</span> $val_list[<span class="number">5</span>].<span class="string">"\n"</span>;        <span class="comment">#天气信息在列表元素5里</span></span><br><span class="line">     <span class="keyword">last</span>;</span><br><span class="line">  </span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br><span class="line">  </span><br><span class="line"><span class="keyword">close</span> HTML;</span><br></pre></td></tr></table></figure>
<p>以上就是代码实现过程，很简单的几行就搞定了。方法很偏门啊，慎用。</p>
<h1 id="运行结果"><a href="#运行结果" class="headerlink" title="运行结果"></a>运行结果</h1><p><img src="https://upload-images.jianshu.io/upload_images/7777712-3f1bc4ea75aee397.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="脚本运行结果"><br>想要获取更准确更实时的数据也可以在网页中继续查找，主要是字符串的定位问题。更简单粗暴的方式是查看数据在哪一行，直接跳到那一行去分解字符串获取数据，这就免得去分析查找的关键字怎么获取了。但这种方法的前提是网页的内容变动不太大，需要的信息总是出现在那一行。就天气来说，网页内容还是比较固定的，可以采用这种方式。</p>

      
    </div>
    
    
    
	<div>
	      
	        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/qgg_blog/2020/02/14/%E7%94%A8perl%E8%84%9A%E6%9C%AC%E8%8E%B7%E5%8F%96%E5%A4%A9%E6%B0%94/">用perl脚本获取天气</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 一只圭工 的个人博客">一只圭工</a></p>
  <p><span>发布时间:</span>2020年02月14日 - 15:02</p>
  <p><span>最后更新:</span>2020年02月14日 - 15:02</p>
  <p><span>原始链接:</span><a href="/qgg_blog/2020/02/14/%E7%94%A8perl%E8%84%9A%E6%9C%AC%E8%8E%B7%E5%8F%96%E5%A4%A9%E6%B0%94/" title="用perl脚本获取天气">https://zhang_de_shuai.gitee.io/qgg_blog/2020/02/14/%E7%94%A8perl%E8%84%9A%E6%9C%AC%E8%8E%B7%E5%8F%96%E5%A4%A9%E6%B0%94/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://zhang_de_shuai.gitee.io/qgg_blog/2020/02/14/%E7%94%A8perl%E8%84%9A%E6%9C%AC%E8%8E%B7%E5%8F%96%E5%A4%A9%E6%B0%94/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>


	      
	</div>

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/qgg_blog/tags/perl/" rel="tag"> <i class="fa fa-tag"></i> perl</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/qgg_blog/2020/02/14/perl%E5%93%88%E5%B8%8C%E6%95%B0%E7%BB%84%E5%AE%9E%E7%8E%B0%E6%8C%87%E4%BB%A4%E8%A1%A8%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" rel="next" title="perl哈希数组实现指令表数据结构">
                <i class="fa fa-chevron-left"></i> perl哈希数组实现指令表数据结构
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/qgg_blog/images/head.jpg"
                alt="一只圭工" />
            
              <p class="site-author-name" itemprop="name">一只圭工</p>
              <p class="site-description motion-element" itemprop="description">我想拥有权利，不是凌驾于别人之上的权利，而是凌驾于自然和科技命运之上的权利，我只想知道事物的运作规律</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/qgg_blog/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/qgg_blog/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/qgg_blog/tags/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/zhang_de_shuai" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-github"></i>Gitee</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#原理"><span class="nav-number">2.</span> <span class="nav-text">原理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#详细分析"><span class="nav-number">3.</span> <span class="nav-text">详细分析</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#代码实现"><span class="nav-number">4.</span> <span class="nav-text">代码实现</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#运行结果"><span class="nav-number">5.</span> <span class="nav-text">运行结果</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一只圭工</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">3.2k</span>
  
</div>

<!--
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>

-->


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      人次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/qgg_blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/qgg_blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/qgg_blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/qgg_blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/qgg_blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/qgg_blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/qgg_blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/qgg_blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/qgg_blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
<script type="text/javascript" src="/js/src/clicklove.js"></script>
